package com.imooc.dianping.exception;

import com.imooc.dianping.common.CommonError;
import com.imooc.dianping.common.CommonRes;
import com.imooc.dianping.enums.EmBusinessError;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常拦截
 */
@ControllerAdvice
public class GlobalExceptionHandle {


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonRes doError(HttpServletRequest servletRequest, Exception ex) {
        if (ex instanceof BusinessException) {
            // 捕获自定义业务异常
            return CommonRes.create(((BusinessException) ex).getCommonError(), "fail");
        } else if (ex instanceof NoHandlerFoundException) {
            // 捕获自404异常找不到路径
            CommonError commonError = new CommonError(EmBusinessError.NO_HANDLE_FOUND);
            return CommonRes.create(commonError, "fail");
        } else if (ex instanceof ServletRequestBindingException) {
            // 请求参数绑定异常
            CommonError commonError = new CommonError(EmBusinessError.BIND_EXCEPTION_ERROR);
            return CommonRes.create(commonError, "fail");
        } else {
            //其他业务异常
            CommonError commonError = new CommonError(EmBusinessError.UMKONW_ERROR);
            return CommonRes.create(commonError, "fail");
        }
    }

}
